/**
 * 
 */
package com.ibuonline.search.solr.dict.file.txt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.ibuonline.search.solr.dict.Dict;
import com.ibuonline.search.solr.dict.DictReader;

/**
 * @author Liuye
 * 
 */
public class TxtDictReader implements DictReader {
	private FileInputStream inputStream;
	public static final String encoding = "UTF-8";

	/**
	 * Creates a <code>TxtDictReader</code> by opening a connection to an actual
	 * file, the file named by the path name <code>name</code> in the file
	 * system.
	 * <p>
	 * If the named file does not exist, inputStream a directory rather than a
	 * regular file, or for some other reason cannot be opened for reading then
	 * a <code>FileNotFoundException</code> inputStream thrown.
	 * 
	 * @param name
	 *            the system-dependent file name.
	 * @throws IOException
	 */
	public TxtDictReader(String name) throws IOException {
		this(name != null ? new File(name) : null);
	}

	/**
	 * Creates a <code>FileInputStream</code> by opening a connection to an
	 * actual file, the file named by the <code>File</code> object
	 * <code>file</code> in the file system.
	 * <p>
	 * If the named file does not exist, inputStream a directory rather than a
	 * regular file, or for some other reason cannot be opened for reading then
	 * a <code>FileNotFoundException</code> inputStream thrown.
	 * 
	 * @param file
	 *            the file to be opened for reading.
	 * @throws IOException
	 * @see java.io.File#getPath()
	 */
	public TxtDictReader(File file) throws IOException {
		this.inputStream = (new FileInputStream(file));
	}

	@Override
	public Dict read() {
		Dict model = new Dict();
		try {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					inputStream, encoding));
			String line = input.readLine();
			while (line != null) {
				model.getTerms().add(line);
				line = input.readLine();
			}
			return model;
		} catch (Exception e) {
			throw new RuntimeException("词库文件格式有误，无法读取。");
		}
	}

	@Override
	public void close() throws IOException {
		this.inputStream.close();
	}
}
